



//
//  MusicDownloadTask.m
//  DownLoadDemo
//
//  Created by lanou3g on 16/4/27.
//  Copyright © 2016年 Liuwx. All rights reserved.
//

#import "MusicDownloadTask.h"

@interface MusicDownloadTask () <NSURLSessionDownloadDelegate>

@property (nonatomic, copy) ProgressBlock progressBlock;
@property (nonatomic, copy) CompleteBlock completeBlock;
@property (nonatomic, strong) NSString *mp3Name;

@end

@implementation MusicDownloadTask

- (void)downloadUrl:(NSURL *)url progressBlock:(ProgressBlock)proBlock complete:(CompleteBlock)comBlock {
    self.progressBlock = proBlock;
    self.completeBlock = comBlock;
    self.mp3Name       = [url.absoluteString stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
    self.mp3Name       = [self.mp3Name stringByReplacingOccurrencesOfString:@":" withString:@"_"];
    
    
    // 网络请求  回调代理方法的时候在主线程里面
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    // 下载任务
    NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithURL:url];
    
    // 启动任务
    [downloadTask resume];
}

// 下载
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
    // 下载进度
    float progress = totalBytesWritten * 1.0 / totalBytesExpectedToWrite;
    // 回调
    self.progressBlock(progress);
    
    
}


// 完成下载
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
   // 得到 Caches文件目录
    NSString *cachesPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
    NSString *filePath = [cachesPath stringByAppendingPathComponent:self.mp3Name];//@"%@.mp3",
    //移动到 cashes文件夹
    [[NSFileManager defaultManager]moveItemAtPath:[location path] toPath:filePath error:nil];
    NSLog(@"%@",filePath);
    
}



@end
